package com.atos.optical.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.atos.optical.common.BaseServiceImpl;
import com.atos.optical.common.ServiceException;
import com.atos.optical.mapper.SysProductTypeInfoMapper;
import com.atos.optical.model.bo.SelectOptionBo;
import com.atos.optical.model.po.SysProductTypeInfo;
import com.atos.optical.model.query.SysProductTypeInfoQuery;
import com.atos.optical.service.SysProductTypeInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wanghra
 * @version 1.0
 * @description
 * @date 2025/8/15
 */
@Slf4j
@Service
public class SysProductTypeInfoServiceImpl extends BaseServiceImpl<SysProductTypeInfoMapper,
        SysProductTypeInfo> implements SysProductTypeInfoService {
    @Autowired
    private SysProductTypeInfoMapper mapper;

    @Override
    public boolean save(SysProductTypeInfo entity) {
        check(entity);
        return super.save(entity);
    }

    @Override
    public boolean updateById(SysProductTypeInfo entity) {
        check(entity);
        return super.updateById(entity);
    }

    @Override
    public SysProductTypeInfoQuery pageByQuery(SysProductTypeInfoQuery query) {
        query.setOrders(OrderItem.descs("CREATE_TIME", "MODIFY_TIME"));
        mapper.pageByQuery(query);
        return query;
    }

    @Override
    public List<SelectOptionBo> getTypeList() {
        List<SelectOptionBo> listOption = new ArrayList<>();
        List<SysProductTypeInfo> list = mapper.selectList(new QueryWrapper<>());
        if (CollUtil.isNotEmpty(list)) {
            list.forEach(typeInfo -> SelectOptionBo.builder()
                    .label(typeInfo.getTypeName())
                    .value(typeInfo.getTypeId())
                    .build());
        }
        return listOption;
    }

    private void check(SysProductTypeInfo entity) {
        if (isExistProductName(entity)) {
            throw new ServiceException("产品类型名称重复！");
        }
    }

    private boolean isExistProductName(SysProductTypeInfo entity) {
        QueryWrapper<SysProductTypeInfo> query = new QueryWrapper<>();
        query.lambda().ne(StrUtil.isNotBlank(entity.getTypeId()), SysProductTypeInfo::getTypeId, entity.getTypeId())
                .eq(SysProductTypeInfo::getTypeName, entity.getTypeName());
        return 0 < mapper.selectCount(query);
    }
}
